﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using AGDN;

namespace Sudum
{
    class EnemyManager
    {
        public static EnemyManager Me { set; get; }
        //the list of enemies
        List<Enemy> enemies = new List<Enemy>();
        GameLevel gameLevel;
        Model enemyModel;
        //the transforms matrix we will load from the model file
        Matrix[] transformMatrix;
        EnemySpawner enemySpawner = new EnemySpawner();
        public EnemyManager(GameLevel level)

        {
            gameLevel = level;
            // load the enemy model
            enemyModel = Sudum.Me.Content.Load<Model>("Models\\Cube");
            //these transforms will not change so we can read it from the start
            transformMatrix = new Matrix[enemyModel.Bones.Count];
            enemyModel.CopyAbsoluteBoneTransformsTo(transformMatrix);

            Me = this;
        }

        public void Update()
        {
            enemySpawner.Update();
            for (int i = 0; i < enemies.Count; i++)
            {
                enemies[i].Update();

                if ((enemies[i].GetPos() - gameLevel.GetTubePosition()).Length() > GameLevel.Current().GetTubeLength())
                {
                    enemies.RemoveAt(i);
                }
            }
        }
        void DrawEnemy(Vector3 pos)
        {

            foreach (ModelMesh mesh in enemyModel.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();

                    effect.VertexColorEnabled = true;
                    effect.TextureEnabled = false;
                    effect.DiffuseColor = Color.White.ToVector3();

                    // apply world transformation here
                    effect.World = transformMatrix[mesh.ParentBone.Index] * Matrix.CreateTranslation(pos) * Matrix.CreateScale(1f) * Matrix.CreateRotationX(gameLevel.GetTubeRotationX());

                    // set current view/projection
                    effect.View = gameLevel.GetLevelCamera().GetView();
                    effect.Projection = gameLevel.GetLevelCamera().GetProjection();
                }

                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }
        }
        public void Draw()
        {
           
            foreach (Enemy enemy in enemies)
            {
                DrawEnemy(enemy.GetPos());
            }
        }
        public void AddEnemy()
        {
            Enemy enemy = new Enemy();
            enemies.Add(enemy);
        }
        public List<Enemy> GetEnemies()
        {
            return enemies;
        }
        public void Remove(int index)
        {
            enemies.RemoveAt(index);
        }
    }
}
